/* 
 * Copyright notice:
 * This file has been taken from the example Google's Chrome to phone extension,
 * and adapted to our needs. (downloaded 01/05/2012 09:00)
 * (see http://code.google.com/p/chrometophone/source/browse/trunk/android/src/com/google/android/apps/chrometophone/DeviceRegistrar.java)
 */

package at.fhj.app.C2DM;

/*

 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import at.fhj.app.R;
import at.fhj.app.util.C2DMRequestHandler;
import at.fhj.app.util.ConnectionInformation;

/**
 * Handles the registration of the client with the FHPI service.
 * 
 * @author Michael Mitteregger <michael.mitteregger.itm09@fh-joanneum.at>
 */
public class C2DMDeviceRegistrar {

    private static final String TAG = "FH2go_C2DMDeviceRegistrar";
    public static final String SENDER_ID = at.fhj.app.util.Configuration.C2DM_SENDER_ID;
    
    /*
     * This intent is fired when the registration status changes.
     */
    public static final String C2DM_REGISTRATION_UPDATE_INTENT = "at.fhj.app.C2DM_REGUPDATE_INTENT";
    public static final String C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUSMESSAGE = "RegChangeStatusMessage";
    public static final String C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUS = "RegChangeStatus";

    public static void registerWithServer(final Context context,
	    final String deviceRegistrationID) {
	new Thread(new Runnable() {
	    public void run() {
		Intent updateStatusIntent = new Intent(C2DM_REGISTRATION_UPDATE_INTENT);

		try {   
		    	// First delete our device id from settings...
        		SharedPreferences settings = C2DMPrefs.get(context);
    		    	SharedPreferences.Editor editor = settings.edit();
    		    	editor.putString("deviceRegistrationID",
    			    deviceRegistrationID);
    		    	editor.commit();
    		    	Log.i(TAG, "Registration success.");
    		    	
    		    	// Now make the unregistration process to the FHPI service...
        		C2DMRequestHandler h = new C2DMRequestHandler();
    		    
        		String response = h
        			.registerClientRequest(deviceRegistrationID);
        		String responseStatus = ConnectionInformation
        			.getConnectionStatus(response);
        
        		if (responseStatus.equals("OK")) {
        		    
        		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUSMESSAGE, "");
        		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUS, true);
        		} else {
        		    Log.w(TAG, "Registration error " + responseStatus);
        		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUSMESSAGE, context.getString(R.string.msg_errorc2dmregister_fhpinotreachable));
        		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUS, false);
        		}
		}
		catch (Exception e) {
		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUSMESSAGE, context.getString(R.string.msg_errorc2dmregister_fhpinotreachable));
		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUS, false);		    
		}
		finally {
		    context.sendBroadcast(updateStatusIntent);
		}
	    }
	}).start();
    }

    public static void unregisterWithServer(final Context context,
	    final String deviceRegistrationID) {
	new Thread(new Runnable() {
	    public void run() {
		Intent updateStatusIntent = new Intent(C2DM_REGISTRATION_UPDATE_INTENT);
		// When unregistering from C2DM, it's not important when the 
		// FHPI server doesn't know about it; it will delete the entry on
		// the server the next time it tries to send a message to this device.
		// (Google servers send a status back that the device is invalid)
		updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUSMESSAGE, "Unregistered Push Notifications.");
		    updateStatusIntent.putExtra(C2DM_REGISTRATION_UPDATE_INTENT_EXTRA_STATUS, true);
		
		C2DMRequestHandler h = new C2DMRequestHandler();

		String response = h
			.unregisterClientRequest(deviceRegistrationID);
		String responseStatus = ConnectionInformation
			.getConnectionStatus(response);

		if (responseStatus.equals("OK")) {
		    SharedPreferences settings = C2DMPrefs.get(context);
		    if (settings.contains("deviceRegistrationID")) {
			SharedPreferences.Editor editor = settings.edit();
			editor.remove("deviceRegistrationID");
			editor.commit();
		    }
		    Log.i(TAG, "Unregistration success.");
		} else {
		    Log.w(TAG, "Unregistration error " + responseStatus);		    
		}
		
		context.sendBroadcast(updateStatusIntent);
	    }
	}).start();
    }
}
